package cn.webrx;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * <p>Project: dictapp - IO
 * <p>Powered by pikachu On 2023-06-26 21:56:04
 * <p>Created by IntelliJ IDEA
 *
 * @author pikachu [729692962@qq.com]
 * @version 1.0
 * @since 17
 */
public class IODemo8 {
    public static void main(String[] args) throws Exception {
        String path = "D:/g.jpg";
        File file = new File(path);
        int num = 5;
        String fn = file.getName();
        long size = file.length();
        // System.out.println(size);
        int n = 1024;
        long block = size % num == 0 ? size / num : size / num + 1;
        int remainder = (int) block % n;


        System.out.println(block);

        try (FileInputStream fis = new FileInputStream(file)) {
            byte[] buf = new byte[n];
            byte[] buf1 = new byte[n];

            int len = 0;
            boolean b = false;
            ok:
            for (int i = 0; i < num; i++) {
                int blocklen = 0;
                String npath = String.format("%s/%s%02d", "D:\\aaa", fn, i);
                try (FileOutputStream fos = new FileOutputStream(npath)) {

                    if (b) {
                        fos.write(buf1, remainder, len);
                        b = false;
                    }

                    while ((len = fis.read(buf)) > 0) {
                        blocklen += len;
                        if (blocklen <= block) {
                            fos.write(buf, 0, len);

                        } else {
                            fos.write(buf, 0, remainder);
                            buf1 = buf;
                            if (i < num - 1) {
                                b = true;
                            }
                            continue ok;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
